//
//  NSString+Calculating.m
//  homework
//
//  Created by 潘 祥 on 14-4-17.
//  Copyright (c) 2014年 Baidu. All rights reserved.
//

#import "NSString+Calculating.h"

@implementation NSString (Calculating)

- (CGSize)stringSizeWithFont:(UIFont *)font constrainWidth:(NSInteger)width {
    return [self stringSizeWithFont:font constrainWidth:width attributeString:nil];
}

- (CGSize)stringSizeWithFont:(UIFont *)font constrainWidth:(NSInteger)width attributeString:(NSDictionary *)attribute {
    NSMutableAttributedString *attributedText = nil;
    if (font) {
        attributedText = [[NSMutableAttributedString alloc] initWithString:self];
        [attributedText setAttributes:@{ NSFontAttributeName:font} range:NSMakeRange(0, self.length)];
        if(attribute){
            [attributedText setAttributes:attribute range:NSMakeRange(0, self.length)];
        }
    } else {
        return CGSizeZero;
    }
    CGRect rect = [attributedText boundingRectWithSize:(CGSize){width,0}
                                               options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
                                               context:nil];
    return rect.size;
}

- (int)returnCharLength {
    int length = 0;
    char *p = (char *)[self cStringUsingEncoding:NSUnicodeStringEncoding];
    for (int i=0 ; i<[self lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {
        if (*p) {
            p++;
            length++;
        } else {
            p++;
        }
    }
    return length;
}

@end
